using System;
using System.Collections.Generic;
using System.Reflection;
using System.Globalization;

using Castle.Core;
using Castle.Core.Logging;
using Castle.Core.Interceptor;
using Castle.MicroKernel;

namespace Castle.Facilities.PolicyInjection
{
    public class PolicyInterceptor : IInterceptor, IOnBehalfAware
    {
        private ComponentPolicy _policy;
        private Type _serviceType;
        private ILogger m_Logger = NullLogger.Instance;

        public ILogger Logger
        {
            get
            {
                return m_Logger;
            }
            set
            {
                m_Logger = value;
            }
        }

        public PolicyInterceptor()
        {
        }

        private void SetHandlersLogger()
        {
            List<Handler> handlerCollection = new List<Handler>();
            foreach (Rule rule in _policy.RuleCollection)
            {
                handlerCollection.AddRange(rule.HandlerCollection);                
            }
            foreach (Handler handler in handlerCollection)
            {
                object handlerInstance = PolicyFacility.HandlerInstanceCollection[handler.TargetType];
                PropertyInfo[] properties = handlerInstance.GetType().GetProperties();
                foreach (PropertyInfo property in properties)
                {
                    if (property.PropertyType == typeof(ILogger))
                    {
                        MethodInfo setMethod = property.GetSetMethod();
                        if (setMethod != null)
                        {
                            object[] parameters = { m_Logger };
                            setMethod.Invoke(handlerInstance, parameters);
                            break;
                        }
                    }
                }
            }
        }

        public void Intercept(IInvocation invocation)
        {
            List<Handler> handlerCollection = new List<Handler>();
            GetHandlerCollection(invocation, handlerCollection);
            HandlerPrecallResult precallResult = ExecutePreCalls(invocation, handlerCollection);
            if (precallResult == HandlerPrecallResult.Continue)
            {
                bool onException = false;
                try
                {
                    invocation.Proceed();    
                }
                catch (Exception ex)
                {
                    onException = true;
                    HandlerOnExceptionResult rethrow = ExecuteOnExceptionCalls(invocation, handlerCollection, ex);
                    if (rethrow == HandlerOnExceptionResult.Rethrow)
                    {
                        throw new InvocationException("Invocation error in " +
                            invocation.InvocationTarget.GetType().FullName + "." + invocation.Method.Name, ex);                        
                    }                    
                }
                if (onException == false)
                {
                    ExecutePostCalls(invocation, handlerCollection);
                }
            }
            else if (precallResult == HandlerPrecallResult.HaltAndException)
            {
                throw new HandlerException("Handler precall pipeline halted " + 
                    invocation.InvocationTarget.GetType().FullName + "." + invocation.Method.Name + 
                    " method execution");
            }
                                               
        }

        private HandlerPrecallResult ExecutePreCalls(IInvocation invocation, List<Handler> handlerCollection)
        {
            try
            {
                foreach (Handler handler in handlerCollection)
                {
                    //note that if it halts, the handler is responsbile to set the return value correctly
                    object handlerInstance = PolicyFacility.HandlerInstanceCollection[handler.TargetType];
                    if (handler.PreCallMethodName != string.Empty)
                    {
                        object[] arguments = { new HandlerContext(invocation, _serviceType) };
                        HandlerPrecallResult precallResult =
                            (HandlerPrecallResult)handler.TargetType.InvokeMember(handler.PreCallMethodName,
                            BindingFlags.InvokeMethod, null, handlerInstance, arguments, CultureInfo.CurrentCulture);
                        if (precallResult != HandlerPrecallResult.Continue)
                        {
                            return precallResult;
                        }
                    }
                }
                return HandlerPrecallResult.Continue;
            }
            catch (Exception ex)
            {
                throw new HandlerException("Handler precall pipeline error", ex);
            }
        }

        private void ExecutePostCalls(IInvocation invocation, List<Handler> handlerCollection)
        {
            try
            {
                foreach (Handler handler in handlerCollection)
                {
                    //note that if it halts, the handler is responsbile to set the return value correctly
                    object handlerInstance = PolicyFacility.HandlerInstanceCollection[handler.TargetType];
                    if (handler.PostCallMethodName != string.Empty)
                    {
                        object[] arguments = { new HandlerContext(invocation, _serviceType) };
                        handler.TargetType.InvokeMember(handler.PostCallMethodName, BindingFlags.InvokeMethod, null,
                            handlerInstance, arguments, CultureInfo.CurrentCulture);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new HandlerException("Handler postcall pipeline error", ex);
            }
        }

        private HandlerOnExceptionResult ExecuteOnExceptionCalls(IInvocation invocation, List<Handler> handlerCollection, 
            Exception invocationException)
        {
            try
            {
                HandlerOnExceptionResult rethrow = HandlerOnExceptionResult.Block;
                foreach (Handler handler in handlerCollection)
                {
                    //note that if it halts, the handler is responsbile to set the return value correctly
                    object handlerInstance = PolicyFacility.HandlerInstanceCollection[handler.TargetType];
                    if (handler.OnExceptionMethodName != string.Empty)
                    {
                        object[] arguments = { new HandlerContext(invocation, _serviceType), invocationException };
                        handler.TargetType.InvokeMember(handler.OnExceptionMethodName, BindingFlags.InvokeMethod, null, 
                            handlerInstance, arguments, CultureInfo.CurrentCulture);
                        HandlerOnExceptionResult currentRetrhow = handler.OnExceptionResult;
                        if ((rethrow == HandlerOnExceptionResult.Block) && (currentRetrhow == HandlerOnExceptionResult.Rethrow))
                        {
                            rethrow = HandlerOnExceptionResult.Rethrow;
                        }
                    }
                }
                return rethrow;
            }
            catch (Exception ex)
            {
                throw new HandlerException("Handler onexception pipeline error", ex);
            }
        }

        private void GetHandlerCollection(IInvocation invocation, List<Handler> handlerCollection)
        {
            foreach (Rule rule in _policy.RuleCollection)
            {
                if (rule.Instance.IsIntercept(invocation, rule.CustomConfigurationAttributeCollection) == true)
                {
                    handlerCollection.AddRange(rule.HandlerCollection);
                }
            }
        }

        public void SetInterceptedComponentModel(ComponentModel target)
        {
            if (target != null)
            {
                _policy = target.ExtendedProperties[Literals.policy] as ComponentPolicy;
                _serviceType = target.Service;
                SetHandlersLogger();
            }
            else
            {
                throw new InvalidOperationException("Invalid target ComponentModel");
            }
        }
    }
}